const { Op } = require('sequelize');
const Pet = require('../models/Pet');
const User = require('../models/User');
const { generatePetAppearance } = require('../utils/petStats');
const petService = require('../services/petService');

const adoptPet = async (req, res) => {
  try {
    const { name, species, appearance, personality, introduction } = req.body;
    const userId = req.user.id;

    // 检查用户是否已经有宠物
    const existingPet = await Pet.findOne({
      where: { userId }
    });

    if (existingPet) {
      return res.status(400).json({
        status: 'error',
        message: '你已经有一只宠物了'
      });
    }

    const pet = await Pet.create({
      name,
      species,
      appearance,
      personality,
      introduction,
      userId,
      energy: 100,
      happiness: 100,
      hunger: 100,
      mood: 100
    });

    res.status(201).json({
      pet
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const getPets = async (req, res) => {
  try {
    const pets = await Pet.findAll({
      where: { userId: req.user.id }
    });

    res.json({
      status: 'success',
      data: { pets }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const getPet = async (req, res) => {
  try {
    const pet = await Pet.findOne({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });

    if (!pet) {
      return res.status(404).json({
        status: 'error',
        message: 'Pet not found'
      });
    }

    res.json({
      status: 'success',
      data: { pet }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const getMyPet = async (req, res) => {
  try {
    const pet = await Pet.findOne({
      where: { userId: req.user.id }
    });

    if (!pet) {
      return res.status(404).json({
        status: 'error',
        message: '未找到宠物'
      });
    }

    res.json({
      pet
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const updatePet = async (req, res) => {
  try {
    console.log('Updating pet with data:', req.body);
    
    const pet = await Pet.findOne({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });

    if (!pet) {
      console.log('Pet not found:', req.params.id);
      return res.status(404).json({
        status: 'error',
        message: '宠物不存在'
      });
    }

    console.log('Current pet stats:', {
      hunger: pet.hunger,
      mood: pet.mood,
      happiness: pet.happiness,
      energy: pet.energy
    });

    // 只允许更新特定字段
    const allowedFields = ['name', 'energy', 'happiness', 'hunger', 'mood'];
    const updates = {};
    
    for (const field of allowedFields) {
      if (req.body[field] !== undefined) {
        // 确保数值在0-100之间
        if (['energy', 'happiness', 'hunger', 'mood'].includes(field)) {
          updates[field] = Math.max(0, Math.min(100, req.body[field]));
        } else {
          updates[field] = req.body[field];
        }
      }
    }

    console.log('Applying updates:', updates);

    // 使用 set 和 save 方法来确保更新生效
    Object.keys(updates).forEach(key => {
      pet[key] = updates[key];
    });
    await pet.save();

    // 重新获取更新后的宠物数据
    const refreshedPet = await Pet.findOne({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });

    console.log('Updated pet stats:', {
      hunger: refreshedPet.hunger,
      mood: refreshedPet.mood,
      happiness: refreshedPet.happiness,
      energy: refreshedPet.energy
    });

    res.json({
      pet: refreshedPet
    });
  } catch (error) {
    console.error('Error updating pet:', error);
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const feedPet = async (req, res) => {
  try {
    const pet = await Pet.findOne({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });

    if (!pet) {
      return res.status(404).json({
        status: 'error',
        message: 'Pet not found'
      });
    }

    // Check if pet was recently fed
    const now = new Date();
    const lastFed = new Date(pet.lastFed);
    const hoursSinceLastFeed = (now - lastFed) / (1000 * 60 * 60);

    if (hoursSinceLastFeed < 4) {
      return res.status(400).json({
        status: 'error',
        message: 'Pet was recently fed'
      });
    }

    pet.hunger = Math.min(100, pet.hunger + 20);
    pet.happiness = Math.min(100, pet.happiness + 10);
    pet.lastFed = now;
    await pet.save();

    res.json({
      status: 'success',
      data: { pet }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const trainPet = async (req, res) => {
  try {
    const pet = await petService.trainPet(req.params.id, req.user.id);
    res.json({
      status: 'success',
      data: { pet }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const mintNFT = async (req, res) => {
  try {
    const pet = await Pet.findOne({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });

    if (!pet) {
      return res.status(404).json({
        status: 'error',
        message: 'Pet not found'
      });
    }

    if (pet.isNFT) {
      return res.status(400).json({
        status: 'error',
        message: 'Pet is already an NFT'
      });
    }

    // Here you would typically interact with your smart contract
    // For now, we'll just simulate the minting process
    const tokenId = `NFT-${Date.now()}`;
    
    pet.isNFT = true;
    pet.tokenId = tokenId;
    await pet.save();

    res.json({
      status: 'success',
      data: { pet }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

// 获取候选宠物（虚拟生成，不属于任何用户）
const candidateSpecies = ['cat', 'dog', 'rabbit', 'hamster', 'parrot'];
const candidatePersonalities = ['active', 'friendly', 'quiet', 'playful'];

const getPetSpeciesLabel = (species) => {
  const labels = {
    cat: '猫咪',
    dog: '狗狗',
    rabbit: '兔子',
    hamster: '仓鼠',
    parrot: '鹦鹉'
  };
  return labels[species] || species;
};

const getPetCandidates = async (req, res) => {
  try {
    // 查询数据库中未被领养（userId为null）的宠物
    const candidates = await Pet.findAll({
      where: { userId: null }
    });

    // 如果没有候选宠物，生成一些新的
    if (!candidates.length) {
      const newCandidates = [];

      for (let i = 0; i < 3; i++) {
        const selectedSpecies = candidateSpecies[Math.floor(Math.random() * candidateSpecies.length)];
        const selectedPersonality = candidatePersonalities[Math.floor(Math.random() * candidatePersonalities.length)];
        const appearance = generatePetAppearance(selectedSpecies);

        const pet = await Pet.create({
          name: `待领养的${getPetSpeciesLabel(selectedSpecies)}`,
          species: selectedSpecies,
          appearance,
          personality: selectedPersonality,
          introduction: `一只${selectedPersonality}的${getPetSpeciesLabel(selectedSpecies)}，正在寻找新主人`,
          userId: null,
          energy: 100,
          happiness: 100,
          hunger: 100,
          mood: 100
        });
        newCandidates.push(pet);
      }
      return res.json({ candidates: newCandidates });
    } else {
      return res.json({ candidates });
    }
  } catch (error) {
    console.error('Error in getPetCandidates:', error);
    return res.status(500).json({ status: 'error', message: error.message });
  }
};

const abandonPet = async (req, res) => {
  try {
    const pet = await Pet.findOne({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });
    if (!pet) {
      return res.status(404).json({
        status: 'error',
        message: '宠物不存在'
      });
    }
    await pet.destroy();
    res.json({
      status: 'success',
      message: '宠物已弃养'
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

const autoRecoverEnergy = async (req, res) => {
  try {
    const pet = await petService.autoRecoverEnergy(req.params.id, req.user.id);
    res.json({
      status: 'success',
      data: { pet }
    });
  } catch (error) {
    res.status(400).json({
      status: 'error',
      message: error.message
    });
  }
};

module.exports = {
  adoptPet,
  getPets,
  getPet,
  getMyPet,
  updatePet,
  feedPet,
  trainPet,
  mintNFT,
  getPetCandidates,
  abandonPet,
  autoRecoverEnergy
};